<template>
  <div class="exam-container">
    <!-- 考试类型选项卡 -->
    <el-card class="exam-tabs-card">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="智能组卷" name="smart">
          <!-- 智能组卷内容 -->
          <div v-if="activeTab === 'smart'">
            <!-- 组卷选项展示 -->
            <el-card class="exam-options-card" v-if="examOptions">
              <template #header>
                <h2 class="section-title">
                  <el-icon class="title-icon">
                    <Document />
                  </el-icon>
                  智能组卷选项
                </h2>
              </template>

              <!-- 横向排列的三个选项组 -->
              <div class="option-row">
                <!-- 考试级别 -->
                <div class="option-group-card">
                  <div class="group-header">
                    <el-icon class="group-icon">
                      <Tickets />
                    </el-icon>
                    <h3 class="group-title">考试级别</h3>
                  </div>
                  <el-select v-model="selectedExamType" class="form-select" @change="fetchKnowledgePoints"
                    placeholder="请选择考试类型">
                    <el-option v-for="type in examOptions.examTypes" :key="type" :label="type"
                      :value="type"></el-option>
                  </el-select>
                </div>

                <!-- 组卷策略 -->
                <div class="option-group-card">
                  <div class="group-header">
                    <el-icon class="group-icon">
                      <SetUp />
                    </el-icon>
                    <h3 class="group-title">组卷策略</h3>
                  </div>
                  <el-select v-model="selectedStrategy" class="form-select" @change="handleStrategyChange"
                    placeholder="请选择组卷策略">
                    <el-option v-for="strategy in examOptions.strategies" :key="strategy.value" :label="strategy.label"
                      :value="strategy.value">
                      <template #default>
                        <div class="strategy-item">
                          <span>{{ strategy.label }}</span>
                          <el-tooltip :content="getStrategyExplanation(strategy.value)" placement="top" effect="light">
                            <el-icon class="strategy-icon">
                              <QuestionFilled />
                            </el-icon>
                          </el-tooltip>
                        </div>
                      </template>
                    </el-option>
                  </el-select>
                </div>

                <!-- 题型数量 - 简化版 -->
                <div class="option-group-card">
                  <div class="group-header">
                    <el-icon class="group-icon"><DataAnalysis /></el-icon>
                    <h3 class="group-title">题型数量</h3>
                  </div>
                  <!-- 单行展示，数字蓝色，无分隔符 -->
                  <div class="question-type-simple">
                    <span>单选<strong class="number">{{ structure.singleChoiceCount }}</strong></span>
                    <span class="plus">+</span>
                    <span>填空<strong class="number">{{ structure.fillBlankCount }}</strong></span>
                    <span class="plus">+</span>
                    <span>主观<strong class="number">{{ structure.subjectiveCount }}</strong></span>
                  </div>
                  <!-- 底部提示文字 -->
                  <div class="question-type-tip">
                    考题数量可能变化，此结构仅供参考
                  </div>
                </div>
              </div>

              <!-- 定向知识点选择部分 -->
              <div class="option-group" v-if="shouldShowKnowledgePoints">
                <div class="group-header">
                  <el-icon class="group-icon">
                    <Collection />
                  </el-icon>
                  <h3 class="group-title">选择知识点</h3>
                </div>
                <!-- 加载状态 -->
                <div v-if="loadingKnowledgePoints" class="loading-container">
                  <el-spinner class="loading-spinner" type="circular" size="40"></el-spinner>
                  <div class="loading-text">加载知识点中...</div>
                </div>

                <!-- 加载完成显示知识点 -->
                <div v-else-if="knowledgePoints.length">
                  <el-checkbox-group v-model="selectedKnowledgePoints" class="knowledge-grid">
                    <el-checkbox v-for="point in knowledgePoints" :key="point.pointId" :label="point.pointId"
                      class="knowledge-point-item">
                      {{ point.pointName }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-else class="empty-tip">
                  <el-empty description="暂无知识点数据" :image-size="80"></el-empty>
                </div>
              </div>
            </el-card>

            <!-- 修改后的按钮逻辑 -->
            <el-card class="exam-actions-card">
              <div class="action-buttons">
                <!-- 如果还没有生成试卷，显示生成试卷按钮 -->
                <el-button 
                  v-if="!generatedExam" 
                  type="primary" 
                  class="btn-generate" 
                  @click="generateExam"
                  :disabled="isGenerating || !validateForm()"
                  :loading="isGenerating"
                >
                  {{ isGenerating ? '智能组卷中...' : '生成试卷' }}
                </el-button>
                
                <!-- 如果已经生成试卷，显示开始考试按钮 -->
                <el-button 
                  v-else
                  type="success" 
                  class="btn-start-exam" 
                  @click="startSmartExam"
                  :icon="VideoPlay"
                >
                  开始考试
                </el-button>
                
                <!-- 重新组卷按钮 -->
                <el-button 
                  v-if="generatedExam"
                  type="info" 
                  class="btn-regenerate" 
                  @click="resetExam"
                  plain
                >
                  重新组卷
                </el-button>
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <!-- 历年套卷部分 -->
        <el-tab-pane label="历年套卷" name="past">
          <el-card class="past-exam-card">
            <template #header>
              <div class="past-exam-header">
                <h2 class="section-title">历年真题套卷</h2>
                <div class="filter-controls">
                  <el-select 
                    v-model="selectedYear" 
                    placeholder="选择年份" 
                    @change="filterPastExams" 
                    clearable
                    class="filter-select"
                  >
                    <el-option v-for="year in availableYears" :key="year" :label="`${year}年`" :value="year" />
                  </el-select>
                  <el-select 
                    v-model="selectedExamLevel" 
                    placeholder="选择级别" 
                    @change="filterPastExams" 
                    clearable
                    class="filter-select"
                  >
                    <el-option label="数学一" value="数一" />
                    <el-option label="数学二" value="数二" />
                    <el-option label="数学三" value="数三" />
                  </el-select>
                </div>
              </div>
            </template>

            <div v-if="loadingPastExams" class="loading-container">
              <el-spinner class="loading-spinner" type="circular" size="40"></el-spinner>
              <div class="loading-text">加载套卷数据中...</div>
            </div>

            <div v-else>
              <!-- 简洁独立卡片布局 -->
              <div class="past-exam-grid">
                <div 
                  v-for="paper in filteredPastExams" 
                  :key="`${paper.examYear}-${paper.examType}`"
                  class="exam-paper-card"
                  @mouseenter="hoveredRow = `${paper.examYear}-${paper.examType}`"
                  @mouseleave="hoveredRow = null"
                >
                  <div class="paper-header">
                    <div class="paper-year">{{ paper.examYear }}年</div>
                    <div class="paper-type">{{ paper.examType }}</div>
                  </div>
                  
                  <div class="paper-content">
  <div class="paper-info">
  <div class="info-label">平均分</div>
  <div class="info-value">{{ formatAvgScore(paper.avgScore) }}</div>
</div>
  <transition name="fade">
    <el-button 
      v-show="hoveredRow === `${paper.examYear}-${paper.examType}`"
      type="primary" 
      size="small"
      @click="startPastExam(paper)"
      class="paper-start-btn"
    >
      开始考试
    </el-button>
  </transition>
</div>
                </div>
              </div>

              <el-empty v-if="filteredPastExams.length === 0" description="暂无相关套卷数据" :image-size="100" />
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 考研数学信息展示表格 -->
    <el-card class="exam-info-card">
      <template #header>
        <h2 class="section-title">考研数学考试信息</h2>
      </template>

      <div class="math-guide-container">
        <div class="exam-info">
          <strong>统一考试时长：</strong> 180分钟（3小时）｜
          <strong>总分：</strong> 150分 ｜
          <strong>最新题型结构：</strong> 选择题10题/填空题6题/解答题6题（2021年修订版）
        </div>

        <table class="math-table">
          <thead>
            <tr>
              <th>卷种</th>
              <th>考试科目与占比</th>
              <th>题型结构（分值）</th>
              <th>建议时间分配</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><strong>数学一</strong></td>
              <td class="subject-detail">
                • 高等数学（56%）<br>
                • 线性代数（22%）<br>
                • 概率统计（22%）
              </td>
              <td class="subject-detail">
                • 选择题：10题 × 5分 = 50分<br>
                • 填空题：6题 × 5分 = 30分<br>
                • 解答题：6题 = 70分
              </td>
              <td class="time-detail">
                • 选择/填空：60-75分钟<br>
                • 解答题：85-95分钟<br>
                • 检查：10-20分钟
              </td>
            </tr>
            <tr>
              <td><strong>数学二</strong></td>
              <td class="subject-detail">
                • 高等数学（78%）<br>
                • 线性代数（22%）<br>
                • 不考概率统计
              </td>
              <td class="subject-detail">
                • 选择题：10题 × 5分 = 50分<br>
                • 填空题：6题 × 5分 = 30分<br>
                • 解答题：6题 = 70分
              </td>
              <td class="time-detail">
                • 选择/填空：60-70分钟<br>
                • 解答题：90-100分钟<br>
                • 检查：10-20分钟
              </td>
            </tr>
            <tr>
              <td><strong>数学三</strong></td>
              <td class="subject-detail">
                • 微积分（56%）<br>
                • 线性代数（22%）<br>
                • 概率统计（22%）
              </td>
              <td class="subject-detail">
                • 选择题：10题 × 5分 = 50分<br>
                • 填空题：6题 × 5分 = 30分<br>
                • 解答题：6题 = 70分
              </td>
              <td class="time-detail">
                • 选择/填空：65-75分钟<br>
                • 解答题：85-95分钟<br>
                • 检查：10-20分钟
              </td>
            </tr>
          </tbody>
        </table>

        <el-alert type="info" :closable="false" class="tips-section">
          <template #title>
            <div class="tips-title">📝 关键说明与备考建议：</div>
          </template>
          <p>1. <strong>题型分布特征</strong>：数学一/三的高数题集中在选择填空前半部分；数学二的高数题占78%需重点突破；证明题多出现在解答题</p>
          <p>2. <strong>时间策略</strong>：选择填空每题控制在4-5分钟，超时先标记；解答题平均10-15分钟/题，中值定理等难题预留时间</p>
          <p>3. <strong>难度说明</strong>：数学一内容最多（三重积分/曲线积分等）；数学二高数深度大；数学三近年难度直逼数学一</p>
          <p>4. <strong>工具限制</strong>：考试禁止使用计算器，需提升手算准确度</p>
        </el-alert>

        <div class="footer-note">
          注：数据根据2021年教育部考试结构调整，适用于2025考研 | 信息更新日期：2025-06-15
        </div>
      </div>
    </el-card>

    <!-- 考试确认弹窗 -->
    <el-dialog
      v-model="examConfirmVisible"
      title="考研数学模拟考试考前须知"
      width="580px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
      class="exam-dialog"
    >
      <div class="exam-requirements">
        <div class="exam-header">
          <el-icon class="exam-header-icon"><Document /></el-icon>
          <h3>请仔细阅读以下考试要求</h3>
        </div>
        
        <div class="requirement-item">
          <el-icon class="requirement-icon"><Clock /></el-icon>
          <div class="requirement-content">
            <strong>考试时长：180分钟</strong>
            <p>考试开始后计时器自动启动，时间到达后系统自动提交试卷</p>
          </div>
        </div>
        
        <div class="requirement-item">
          <el-icon class="requirement-icon"><Monitor /></el-icon>
          <div class="requirement-content">
            <strong>专注要求：请勿离开考试界面</strong>
            <p>考试期间切换窗口、最小化浏览器等行为将被记录</p>
          </div>
        </div>
        
        <div class="requirement-item">
          <el-icon class="requirement-icon"><Warning /></el-icon>
          <div class="requirement-content">
            <strong>诚信考试：禁止使用辅助工具</strong>
            <p>禁止使用计算器、查阅资料、与他人交流，请诚信应考</p>
          </div>
        </div>
        
        <el-alert 
          type="warning" 
          :closable="false" 
          class="exam-alert"
          show-icon
        >
          <template #title>
            <strong>⚠️ 重要提醒</strong>
          </template>
          考试开始后将无法返回重新组卷，请确保已充分准备。建议在安静环境中进行考试。
        </el-alert>
      </div>
      
      <div class="exam-confirm-section">
        <el-checkbox v-model="examAgreed" size="large">
          <span class="confirm-text">我已阅读考试要求，准备开始考试</span>
        </el-checkbox>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="examConfirmVisible = false" size="large">
            取消考试
          </el-button>
          <el-button 
            type="primary" 
            @click="confirmStartExam"
            :disabled="!examAgreed"
            size="large"
            :icon="VideoPlay"
          >
            确认开始考试
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 错误信息展示 -->
    <el-alert v-if="errorMessage" type="error" show-icon :message="errorMessage" class="error-message"></el-alert>
  </div>
</template>

<script>
import { ref, onMounted, watch, computed, nextTick, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { useUserStore } from '@/store/user';
import {
  QuestionFilled,
  Document,
  Tickets,
  SetUp,
  DataAnalysis,
  Collection,
  Clock,
  Monitor,
  Warning,
  VideoPlay
} from '@element-plus/icons-vue';

export default {
  components: {
    QuestionFilled,
    Document,
    Tickets,
    SetUp,
    DataAnalysis,
    Collection,
    Clock,
    Monitor,
    Warning,
    VideoPlay
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const userStore = useUserStore();
    const router = useRouter();
    const isGenerating = ref(false);
    const generatedExam = ref(null);
    const errorMessage = ref('');
    const activeTab = ref('smart');
    const loadingPastExams = ref(false);
    const loadingKnowledgePoints = ref(false);

    // 新增考试确认弹窗相关状态
    const examConfirmVisible = ref(false);
    const examAgreed = ref(false);
    const currentExamInfo = ref(null); // 存储当前要开始的考试信息

    // 历年套卷相关数据
    const pastExamStats = ref([]);
    const availableYears = ref([]);
    const pastExamPapers = ref([]);
    const filteredPastExams = ref([]);
    const selectedYear = ref(null);
    const selectedExamLevel = ref(null);
    const hoveredRow = ref(null);

    // 获取历年套卷数据
    const fetchPastExamStats = async () => {
  loadingPastExams.value = true;
  try {
    const res = await axios.get('/api/exam/past-exams/stats');
    console.log('API返回数据:', res.data); // 添加这行
    
    if (res.data.code === 200) {
      pastExamPapers.value = res.data.data.map(item => ({
        examYear: item.examYear,
        examType: item.examType,
        totalQuestions: item.totalQuestions,
        avgScore: item.avgScore // 确保这里正确赋值
      }));
      
      console.log('处理后数据:', pastExamPapers.value); // 添加这行
      filteredPastExams.value = [...pastExamPapers.value];
    }
  } catch (error) {
    console.error('获取历年套卷数据失败:', error);
  } finally {
    loadingPastExams.value = false;
  }
};

    // 根据年份和级别筛选
    const filterPastExams = () => {
      let filtered = [...pastExamPapers.value];
      
      if (selectedYear.value) {
        filtered = filtered.filter(p => p.examYear === selectedYear.value);
      }
      
      if (selectedExamLevel.value) {
        filtered = filtered.filter(p => p.examType === selectedExamLevel.value);
      }
      
      filteredPastExams.value = filtered;
    };

    // 标签类型
    const getTagType = (type) => {
      return {
        '数一': 'danger',
        '数二': 'warning',
        '数三': 'success'
      }[type] || '';
    };

    // 考试选项数据
    const examOptions = ref({
      examTypes: ['数一', '数二', '数三'],
      strategies: [
        { value: 'random', label: '完全随机' },
        { value: 'weakness', label: '薄弱点强化' },
        { value: 'high_frequency', label: '高频易错题' },
        { value: 'custom', label: '定向知识点' }
      ]
    });

    // 知识点相关数据
    const knowledgePoints = ref([]);
    const selectedExamType = ref('数一');
    const selectedStrategy = ref('');
    const selectedKnowledgePoints = ref([]);

    // 考试题型结构
    const structure = computed(() => {
      if (selectedExamType.value === '数三') {
        return {
          singleChoiceCount: 10,
          fillBlankCount: 6,
          subjectiveCount: 8
        };
      } else if (selectedExamType.value === '数一' || selectedExamType.value === '数二') {
        return {
          singleChoiceCount: 10,
          fillBlankCount: 6,
          subjectiveCount: 6
        };
      }
      return {
        singleChoiceCount: 0,
        fillBlankCount: 0,
        subjectiveCount: 0
      };
    });

    // 表单验证
    const validateForm = () => {
      const basicValid = (
        selectedExamType.value &&
        selectedStrategy.value &&
        structure.value.singleChoiceCount >= 0 &&
        structure.value.fillBlankCount >= 0 &&
        structure.value.subjectiveCount >= 0 &&
        (structure.value.singleChoiceCount +
          structure.value.fillBlankCount +
          structure.value.subjectiveCount) > 0
      );

      if (selectedStrategy.value === 'custom') {
        return basicValid && selectedKnowledgePoints.value.length > 0;
      }

      return basicValid;
    };

    // 获取知识点列表
    const fetchKnowledgePoints = async (strategy = selectedStrategy.value) => {
      if (strategy !== 'custom') {
        return;
      }

      if (!selectedExamType.value) {
        return;
      }

      errorMessage.value = '';
      loadingKnowledgePoints.value = true;

      try {
        const response = await axios.get('/api/exam/knowledge-points', {
          params: {
            examType: selectedExamType.value
          }
        });

        if (response.data.code === 200) {
          knowledgePoints.value = response.data.data.knowledgePoints || [];
        } else {
          knowledgePoints.value = [];
          errorMessage.value = '获取知识点失败: ' + (response.data.msg || '未知错误');
        }
      } catch (error) {
        console.error('获取知识点失败:', error);
        knowledgePoints.value = [];
        errorMessage.value = '加载知识点失败，请稍后重试';
      } finally {
        loadingKnowledgePoints.value = false;
      }
    };

    // 处理策略变化
    const handleStrategyChange = (newVal) => {
      selectedKnowledgePoints.value = [];

      if (newVal === 'custom') {
        nextTick(() => {
          fetchKnowledgePoints('custom');
        });
      }
    };

    // 修改后的组卷方法 - 简化返回结果
    const generateExam = async () => {
      if (!validateForm()) {
        errorMessage.value = '请填写完整的组卷信息';
        return;
      }

      isGenerating.value = true;
      errorMessage.value = '';

      try {
        const timeLimit = 180;
        const userId = Number(userStore.userId);
        
        if (!userId || isNaN(userId)) {
          throw new Error('用户ID无效，请重新登录');
        }

        const payload = {
          examType: selectedExamType.value,
          strategy: selectedStrategy.value,
          questionStructure: {
            singleChoice: structure.value.singleChoiceCount,
            fillBlank: structure.value.fillBlankCount,
            subjective: structure.value.subjectiveCount
          },
          knowledgePoints: selectedStrategy.value === 'custom'
            ? selectedKnowledgePoints.value
            : null,
          timeLimit: timeLimit
        };

        const response = await axios.post('/api/exam/generate', payload, {
          headers: {
            'Content-Type': 'application/json',
            'userId': userId.toString()
          }
        });

        if (response.data.code === 200) {
          generatedExam.value = {
            examId: response.data.data.examId,
            examType: selectedExamType.value,
            strategy: selectedStrategy.value,
            createdAt: new Date()
          };
          
          proxy.$message.success({
            message: '🎉 试卷生成成功！点击"开始考试"进入考试界面',
            duration: 3000,
            showClose: true
          });
        } else {
          errorMessage.value = `组卷失败: ${response.data.msg || '未知错误'}`;
        }
      } catch (error) {
        console.error('组卷失败:', error);
        if (error.response?.data) {
          errorMessage.value = error.response.data.message || JSON.stringify(error.response.data);
        } else if (error.message.includes('用户ID无效')) {
          errorMessage.value = '请重新登录';
          router.push('/login');
        } else {
          errorMessage.value = '网络错误，请稍后重试';
        }
      } finally {
        isGenerating.value = false;
      }
    };

    // 开始智能组卷考试
    const startSmartExam = () => {
      currentExamInfo.value = {
        type: 'smart',
        examId: generatedExam.value.examId
      };
      showExamConfirmDialog();
    };

    // 开始历年套卷考试
    const startPastExam = (paper) => {
      currentExamInfo.value = {
        type: 'past',
        examType: paper.examType,
        examYear: paper.examYear
      };
      showExamConfirmDialog();
    };

    // 显示考试确认弹窗
    const showExamConfirmDialog = () => {
      examAgreed.value = false;
      examConfirmVisible.value = true;
    };

    // 确认开始考试
    const confirmStartExam = () => {
      if (!examAgreed.value) {
        proxy.$message.warning('请先阅读并确认考试要求');
        return;
      }
      
      examConfirmVisible.value = false;
      
      proxy.$message.info({
        message: '正在跳转到考试界面，祝您考试顺利！',
        duration: 2000
      });
      
      setTimeout(() => {
        if (currentExamInfo.value && currentExamInfo.value.type === 'past') {
          router.push({
            name: 'Test',
            query: {
              isPastExam: true,
              examType: currentExamInfo.value.examType,
              examYear: currentExamInfo.value.examYear
            }
          });
        } else {
          router.push({
            name: 'Test',
            query: {
              examId: generatedExam.value.examId,
              timeLimit: 180
            }
          });
        }
        currentExamInfo.value = null;
      }, 500);
    };

    // 重新组卷
    const resetExam = () => {
      generatedExam.value = null;
      examAgreed.value = false;
      proxy.$message.info('已重置，可重新进行组卷设置');
    };

    // 辅助方法
    const getStrategyName = (strategy) => {
      return examOptions.value.strategies.find(s => s.value === strategy)?.label || strategy;
    };

    const getQuestionTypeName = (type) => {
      const typeMap = {
        single_choice: '单选题',
        fill_in_the_blank: '填空题',
        subjective: '主观题'
      };
      return typeMap[type] || type;
    };

    const getSubjectIdsByExamType = (examType) => {
      switch (examType) {
        case '数一': return [1, 2, 3];
        case '数二': return [1, 2];
        case '数三': return [1, 2, 3];
        default: return [];
      }
    };

    const formatQuestionContent = (content) => {
      if (!content) return '';
      return content
        .replace(/\\n/g, '<br>')
        .replace(/\$/g, '$$$');
    };

    const isObjectiveQuestion = (type) => {
      return ['single_choice', 'fill_in_the_blank'].includes(type);
    };

    const getQuestionOptions = (question) => {
      try {
        if (question.questionType === 'single_choice' && question.options) {
          return typeof question.options === 'string'
            ? JSON.parse(question.options)
            : question.options;
        }
      } catch (e) {
        console.error('解析选项失败:', e);
      }
      return {};
    };

    const formatDate = (date) => {
      if (!date) return '';
      const d = new Date(date);
      return isNaN(d.getTime())
        ? ''
        : d.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
    };
    const formatAvgScore = (score) => {
  if (score === null || score === undefined) return '--';
  const num = Number(score);
  return isNaN(num) ? '--' : Math.round(num);
};

    const getStrategyExplanation = (strategy) => {
      switch (strategy) {
        case 'random':
          return '从题库中完全随机抽取题目组成试卷。';
        case 'weakness':
          return '根据用户的历史答题数据，重点抽取用户薄弱知识点的题目进行组卷。';
        case 'high_frequency':
          return '选取题库中出现频率较高且容易出错的题目组成试卷。';
        case 'custom':
          return '用户自主选择知识点，系统根据所选知识点进行组卷。';
        default:
          return '';
      }
    };

    const goToPastExam = (paper) => {
      router.push({
        name: 'Test',
        query: {
          isPastExam: true,
          examType: paper.examType,
          examYear: paper.examYear
        }
      });
    };

    // 监听考试类型变化
    watch(selectedExamType, (newVal) => {
      if (selectedStrategy.value === 'custom') {
        selectedKnowledgePoints.value = [];
        fetchKnowledgePoints();
      }
    });

    // 初始化
    onMounted(() => {
      selectedExamType.value = '数一';
      fetchPastExamStats();
    });

    return {
      activeTab,
      examOptions,
      selectedExamType,
      selectedStrategy,
      knowledgePoints,
      selectedKnowledgePoints,
      structure,
      isGenerating,
      generatedExam,
      errorMessage,
      generateExam,
      getStrategyName,
      getQuestionTypeName,
      formatQuestionContent,
      isObjectiveQuestion,
      getQuestionOptions,
      formatDate,
      validateForm,
      shouldShowKnowledgePoints: computed(() => selectedStrategy.value === 'custom'),
      getStrategyExplanation,
      pastExamStats,
      availableYears,
      selectedYear,
      selectedExamLevel,
      hoveredRow,
      fetchPastExamStats,
      goToPastExam,
      getTagType,
      loadingPastExams,
      pastExamPapers,
      filteredPastExams,
      filterPastExams,
      startPastExam,
      startSmartExam,
      loadingKnowledgePoints,
      handleStrategyChange,
      fetchKnowledgePoints,
      examConfirmVisible,
      examAgreed,
      currentExamInfo,
      showExamConfirmDialog,
      confirmStartExam,
      resetExam,
      formatAvgScore
    };
  }
};
</script>

<style scoped>
/* 新增样式 */
.option-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.option-group-card {
  flex: 1;
  background: #f8fafc;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.option-group-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.group-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.group-icon {
  font-size: 18px;
  margin-right: 10px;
  color: #3498db;
  background: #e3f2fd;
  padding: 6px;
  border-radius: 6px;
}

.group-title {
  font-size: 16px;
  color: #2d3748;
  margin: 0;
  font-weight: 600;
}

/* 题型数量样式 */
.question-type-simple {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px 0;
  gap: 5px;
}

.question-type-simple .plus {
  color: #999;
  margin: 0 8px;
  font-weight: normal;
}

.question-type-simple .number {
  color: #409EFF;
  margin: 0 2px;
  font-weight: 600;
}

.question-type-simple > span:not(.plus) {
  font-size: 16px;
  color: #4a5568;
}

.question-type-tip {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-top: 5px;
  line-height: 1.4;
}

.title-icon {
  margin-right: 10px;
  color: #3498db;
}

/* 按钮相关样式 */
.action-buttons {
  display: flex;
  flex-direction: row;
  gap: 15px;
  align-items: center;
  justify-content: center;
}

.btn-generate {
  width: 100%;
  max-width: 300px;
  padding: 12px 0;
  font-size: 16px;
  background-color: #409EFF;
  border-color: #409EFF;
}

.btn-generate:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.btn-start-exam,
.btn-regenerate {
  flex: 1;
  max-width: 180px;
  padding: 12px 20px;
  font-size: 16px;
}

.btn-start-exam {
  background-color: #67C23A;
  border-color: #67C23A;
}

.btn-start-exam:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

/* 弹窗整体样式 */
:deep(.exam-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #1e40af, #2563eb);
  color: white;
  padding: 16px 24px;
  border-radius: 8px 8px 0 0;
}

:deep(.exam-dialog .el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 16px;
}

:deep(.exam-dialog .el-dialog__body) {
  padding: 0;
}

/* 考试确认弹窗样式 */
.exam-requirements {
  padding: 20px 24px 15px 24px;
  background: linear-gradient(135deg, #f7faff, #eff6ff);
  border-radius: 0;
  border: none;
  margin: 0;
}

.exam-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  justify-content: center;
  padding-bottom: 15px;
  border-bottom: 2px solid #2563eb;
}

.exam-header-icon {
  font-size: 22px;
  color: #1e40af;
  margin-right: 10px;
}

.exam-header h3 {
  margin: 0;
  color: #1e3a8a;
  font-size: 18px;
  font-weight: 600;
}

.requirement-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  padding: 12px 15px;
  background: linear-gradient(135deg, #ffffff, #f8faff);
  border-radius: 6px;
  border-left: 3px solid #2563eb;
  border: 1px solid #e2e8f0;
  transition: all 0.2s ease;
}

.requirement-item:hover {
  transform: translateX(3px);
  box-shadow: 0 2px 8px rgba(37, 99, 235, 0.1);
  border-color: #3b82f6;
}

.requirement-icon {
  margin-right: 12px;
  color: #1e40af;
  font-size: 16px;
  flex-shrink: 0;
  margin-top: 2px;
  background: #eff6ff;
  padding: 4px;
  border-radius: 4px;
}

.requirement-content {
  flex: 1;
}

.requirement-content strong {
  display: block;
  color: #1e3a8a;
  margin-bottom: 3px;
  font-size: 14px;
  font-weight: 600;
}

.requirement-content p {
  margin: 0;
  color: #475569;
  font-size: 12px;
  line-height: 1.4;
}

.exam-alert {
  margin: 20px 0 0 0;
  border-radius: 8px;
}

.exam-confirm-section {
  margin: 20px 24px 20px 24px;
  padding: 0;
  background: none;
  border: none;
  box-shadow: none;
}

.exam-confirm-section :deep(.el-checkbox) {
  align-items: flex-start;
}

.exam-confirm-section :deep(.el-checkbox__input) {
  margin-top: 2px;
}

.exam-confirm-section :deep(.el-checkbox__inner) {
  border-color: #94a3b8;
}

.exam-confirm-section :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #1e40af;
  border-color: #1e40af;
}

.confirm-text {
  font-size: 13px;
  color: #475569;
  line-height: 1.4;
  font-weight: 400;
  letter-spacing: 0.3px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-top: 10px;
}

.dialog-footer .el-button {
  min-width: 120px;
  padding: 10px 24px;
  font-size: 14px;
}

.dialog-footer .el-button--primary {
  background-color: #1e40af;
  border-color: #1e40af;
}

.dialog-footer .el-button--primary:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .option-row {
    flex-direction: column;
    gap: 15px;
  }

  .option-group-card {
    width: 100%;
  }

  .question-type-simple {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .question-type-simple {
    gap: 3px;
    flex-wrap: wrap;
  }

  .question-type-simple .plus {
    margin: 0 5px;
  }

  .exam-requirements {
    padding: 15px 20px 12px 20px;
  }

  .requirement-item {
    padding: 10px 12px;
    margin-bottom: 10px;
  }

  .exam-confirm-section {
    margin: 15px 20px 15px 20px;
    padding: 0;
  }

  .action-buttons {
    flex-direction: column;
    gap: 10px;
  }

  .btn-start-exam,
  .btn-regenerate {
    max-width: 100%;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 10px;
  }

  .dialog-footer .el-button {
    width: 100%;
  }
}

.exam-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.section-title {
  font-size: 20px;
  color: #303133;
  margin: 0;
  font-weight: 600;
}

.exam-info-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.exam-tabs-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.exam-options-card,
.exam-actions-card,
.exam-result-card,
.past-exam-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

/* 数学信息表格样式 */
.math-guide-container {
  font-family: 'Microsoft YaHei', sans-serif;
  padding: 10px;
}

.exam-info {
  background: linear-gradient(135deg, #e3f2fd, #bbdefb);
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-size: 16px;
  border-left: 4px solid #2196f3;
}

.math-table {
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.math-table th {
  background: linear-gradient(to bottom, #3498db, #2980b9);
  color: white;
  font-weight: bold;
  padding: 14px;
  text-align: center;
  border: 1px solid #2980b9;
}

.math-table td {
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  text-align: center;
}

.math-table tr:nth-child(even) {
  background-color: #f5f9ff;
}

.math-table tr:hover {
  background-color: #e3f2fd;
  transition: background-color 0.3s;
}

.subject-detail {
  text-align: left;
  line-height: 1.6;
}

.time-detail {
  font-weight: 500;
  color: #e74c3c;
}

.tips-section {
  margin-top: 25px;
}

.tips-title {
  color: #f57c00;
  font-weight: bold;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.footer-note {
  text-align: center;
  margin-top: 20px;
  color: #7f8c8d;
  font-size: 14px;
}

@media (max-width: 768px) {
  .math-table {
    display: block;
    overflow-x: auto;
  }
}

/* 其他原有样式 */
.empty-content {
  padding: 40px 0;
}

.option-group {
  margin-bottom: 20px;
}

.form-select {
  width: 100%;
}

.form-input {
  width: 100px;
}

.strategy-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.strategy-icon {
  color: #409EFF;
  cursor: pointer;
}

/* 优化后的知识点网格布局 */
.knowledge-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  margin-top: 10px;
}

.knowledge-point-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  transition: all 0.3s ease;
  margin: 0;
  font-size: 14px;
}

.knowledge-point-item:hover {
  background-color: #e4e7ed;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.knowledge-point-item.is-checked {
  background-color: #ecf5ff;
  border-color: #409EFF;
  color: #409EFF;
}

@media (max-width: 992px) {
  .knowledge-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .knowledge-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .knowledge-grid {
    grid-template-columns: 1fr;
  }
}

.题型设置 {
  display: flex;
  gap: 20px;
}

.题型-item {
  display: flex;
  align-items: center;
}

.questions-preview {
  margin-top: 20px;
}

.question-item {
  margin-bottom: 16px;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.question-index {
  font-weight: bold;
  margin-right: 10px;
}

.question-type-badge {
  margin-left: auto;
}

.question-content {
  margin-bottom: 10px;
  white-space: pre-wrap;
  line-height: 1.6;
}

.options {
  margin-left: 20px;
  padding-left: 10px;
  border-left: 2px solid #EBEEF5;
}

.option {
  margin: 8px 0;
}

.error-message {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .exam-info-card {
    overflow-x: auto;
  }

  .题型设置 {
    flex-direction: column;
    gap: 10px;
  }

  .题型-item {
    width: 100%;
  }

  .btn-generate,
  .btn-start-exam {
    padding: 10px 0;
  }
}

.subject-type-wrapper {
  display: flex;
  gap: 16px;
  align-items: center;
}

.subject-badge,
.type-badge {
  flex: 1;
  max-width: 300px;
}

.param-badge {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.param-badge .el-tag {
  margin-bottom: 4px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  border-radius: 8px 8px 0 0 !important;
  margin-right: 8px;
}

:deep(.el-tabs--card > .el-tabs__header) {
  border-bottom: none;
}

.past-exam-card {
  border-radius: 8px;
}

/* 简洁独立卡片式历年套卷样式 */
.past-exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-select {
  width: 130px;
}

.past-exam-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 16px;
  margin-top: 20px;
}

.exam-paper-card {
  background: #ffffff;
  border-radius: 6px;
  padding: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  border: 1px solid #e8e9ea;
  transition: all 0.3s ease;
  cursor: pointer;
  height: 85px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.exam-paper-card:hover {
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  border-color: #409EFF;
}

.paper-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.paper-year {
  font-size: 15px;
  font-weight: 600;
  color: #2c3e50;
}

.paper-type {
  background: #f0f2f5;
  color: #606266;
  font-size: 12px;
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 12px;
}

.paper-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.paper-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.info-label {
  font-size: 11px;
  color: #909399;
}

.info-value {
  font-size: 12px;
  font-weight: 600;
  color: #409EFF;
}

.paper-start-btn {
  font-size: 11px;
  padding: 4px 12px;
  border-radius: 4px;
  background-color: #409EFF;
  border-color: #409EFF;
  min-width: 70px;
  height: 24px;
}

.paper-start-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
}

/* 按钮淡入淡出动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .past-exam-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 14px;
  }
}

@media (max-width: 768px) {
  .past-exam-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-controls {
    justify-content: center;
  }
  
  .filter-select {
    flex: 1;
    max-width: 150px;
  }
  
  .past-exam-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .exam-paper-card {
    padding: 10px;
    height: 75px;
  }
  
  .paper-year {
    font-size: 14px;
  }
  
  .paper-type {
    font-size: 11px;
    padding: 2px 6px;
  }
  

  
  .paper-start-btn {
    font-size: 10px;
    padding: 3px 8px;
    min-width: 60px;
    height: 20px;
  }
}

@media (max-width: 480px) {
  .past-exam-grid {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  
  .exam-paper-card {
    padding: 8px;
    height: 70px;
  }
  
  .paper-year {
    font-size: 13px;
  }
  
  .paper-type {
    font-size: 10px;
    padding: 1px 5px;
  }
}

.loading-container {
  height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 1rem;
}

.loading-spinner {
  color: #1890ff;
}

.loading-text {
  font-size: 1.1rem;
  color: #666;
}

.paper-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-bottom: 8px;
}

.info-label {
  font-size: 11px;
  color: #909399;
}

.info-value {
  font-size: 12px;
  font-weight: 600;
  color: #70c0e8; /* 改为浅蓝色 */
}
</style>